//
//  AXFHomeViewController.m
//  AXFEightGroup
//
//  Created by ooops on 12/22/16.
//  Copyright © 2016 ya. All rights reserved.
//

#import "AXFHomeViewController.h"
#import "AXFDataModel.h"
#import "AXFDeliverAddressController.h"
#import "AXFHomeTitleView.h"
#import "WaterFlowLayout.h"

#import "AXFDetailViewController.h"
#import "AXFShoppingButtonView.h"
#import "AXFSearchViewController.h"
#import "AXFBrowserViewController.h"

#import "AXFCarouselCollectionViewCell.h"
#import "AXFActivitiesCollectionViewCell.h"
#import "AXFIconsCollectionViewCell.h"
#import "WaterFlowCollectionViewCell.h"
#import "AXFScanViewController.h"


@interface AXFHomeViewController ()<UIGestureRecognizerDelegate, XRCarouselViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,CAAnimationDelegate>
@property(nonatomic,strong)UILabel*locationLabel;
@property(nonatomic,weak)AXFHomeTitleView*titleView;

@property (nonatomic, strong) UICollectionView *collectionView;                                 /** collectionView */
@property (nonatomic, strong) NSArray<NSArray<AXFDataModel *> *> *collectionArray;              /** collectionViewArray */

@end

@implementation AXFHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupCollectionView];
    [self setupNotifications];
    [self setupNavigationBar];
    [self loadDeliverAddressArray];
    [self loadData];
}
#pragma mark - 数据请求
- (void)loadData {
    [_ModelMgr homeData:^(NSArray<NSArray<AXFDataModel *> *> * _Nonnull models) {
        self.collectionArray = models;
        [self.collectionView reloadData];
    }];
}


-(void)loadDeliverAddressArray
{
    [_ModelMgr myAdress:^(NSArray<AXFDataModel *> * _Nonnull myAdressModels) {
        
        [self handleDeliverAddressArray:(myAdressModels)];
    }];
}


-(void)handleDeliverAddressArray:(NSArray<AXFDataModel *> *)array
{
    NSString*string=array[0].address;
    string=[string sj_beforeString:@" "];
    _titleView.locationLabel.text=string;
    _titleView.locationLabel.hidden=NO;
}


-(void)setupNavigationBar
{
    UITapGestureRecognizer*tapGestureRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickedToSelectLocation:)];
    _titleView=[AXFHomeTitleView loadView];
    [_titleView addGestureRecognizer:tapGestureRecognizer];
    self.navigationItem.titleView=_titleView;
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:1.00 green:0.85 blue:0.00 alpha:1.00];
    UIButton*scanButton=[self buttonWithTitle:@"扫一扫" ImageName:@"icon_black_scancode"];
    [scanButton addTarget:self action:@selector(clickedScanButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:scanButton];
    
    UIButton*searchButton=[self buttonWithTitle:@"搜索" ImageName:@"icon_search"];
    [searchButton addTarget:self action:@selector(clickedSearchButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:searchButton];
}


-(UIButton*)buttonWithTitle:(NSString*)title ImageName:(NSString*)imageName
{
    UIButton*button=[[UIButton alloc]initWithFrame:CGRectZero];
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font=[UIFont systemFontOfSize:10];
    [button sizeToFit];
    CGSize imageSize=button.imageView.frame.size;
    CGSize titleSize=button.titleLabel.frame.size;
    button.titleEdgeInsets=UIEdgeInsetsMake(0, -imageSize.width, -imageSize.height-2, 0);
    button.imageEdgeInsets=UIEdgeInsetsMake(-titleSize.height-2, 0, 0, -titleSize.width);
    return button;
}

#pragma mark - 导航条右侧搜索按钮
-(void)clickedSearchButton:(UIBarButtonItem*)searchButton
{
    [self.navigationController pushViewController:[AXFSearchViewController new] animated:YES];
}

-(void)clickedScanButton:(UIBarButtonItem*)scanButton
{
    UIStoryboard*stroyboard=[UIStoryboard storyboardWithName:@"AXFDetailAddressController" bundle:nil];
    
    AXFScanViewController*vc=[stroyboard instantiateViewControllerWithIdentifier:@"ScanView"];
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)clickedToSelectLocation:(UITapGestureRecognizer*)tapGestureRecognizer
{
    AXFDeliverAddressController*vc=[[AXFDeliverAddressController alloc]init];
    __weak typeof(self)weakSelf=self;
    [vc setSelectAddressBlock:^(AXFDataModel*dataModel)
    {
        __strong typeof(weakSelf) strongSelf=weakSelf;
        [strongSelf handleDeliverAddressArray:@[dataModel]];
    }];

    
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark 轮播器点击事件代理XRCarouselViewDelegate
- (void)carouselView:(XRCarouselView *)carouselView clickImageAtIndex:(NSInteger)index {
    NSLog(@"点击了第%ld张图片", (long)index);
}

#pragma mark - 配置collectionView信息
- (void)setupCollectionView {
    WaterFlowLayout *waterFlowLayout = [WaterFlowLayout new];
    _collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:waterFlowLayout];
    _collectionView.backgroundColor = [UIColor sj_colorWithHex:0xEFEFEF];
    
    _collectionView.delegate = self;
    _collectionView.dataSource  = self;
    
    [_collectionView registerNib:[UINib nibWithNibName:@"WaterFlowCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"WaterFlowCollectionViewCell"];
    [_collectionView registerClass:[AXFCarouselCollectionViewCell class] forCellWithReuseIdentifier:@"AXFCarouselCollectionViewCell"];
    [_collectionView registerClass:[AXFActivitiesCollectionViewCell class] forCellWithReuseIdentifier:@"AXFActivitiesCollectionViewCell"];
    [_collectionView registerClass:[AXFIconsCollectionViewCell class] forCellWithReuseIdentifier:@"AXFIconsCollectionViewCell"];
    //AXFIconsCollectionViewCell
    self.view = _collectionView;
}


#pragma mark - UICollectionView DataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.collectionArray.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    switch (section) {
        case 1:case 2:case 3:return self.collectionArray[section].count;break;
        default:return 1;break;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0: {
            AXFCarouselCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AXFCarouselCollectionViewCell" forIndexPath:indexPath];
            cell.models = self.collectionArray[indexPath.section];
            cell.carouselView.delegate = self; // 轮播器图片点击代理
            return cell;
        }
            break;
        case 1: {
            AXFIconsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AXFIconsCollectionViewCell" forIndexPath:indexPath];
            cell.model = self.collectionArray[indexPath.section][indexPath.item];
            //cell.backgroundColor = [UIColor sj_randomColor];
            return cell;
        }
            break;
        case 2: {
            AXFActivitiesCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AXFActivitiesCollectionViewCell" forIndexPath:indexPath];
            cell.model = self.collectionArray[indexPath.section][indexPath.item];
            return cell;
        }
            break;
        case 3: {
            WaterFlowCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WaterFlowCollectionViewCell" forIndexPath:indexPath];
            cell.model = self.collectionArray[indexPath.section][indexPath.item];
            //cell.backgroundColor = [UIColor sj_randomColor];
            return cell;
        }
            break;
        default:
            break;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if([[collectionView cellForItemAtIndexPath:indexPath] isKindOfClass:[UICollectionViewCell class]]) {
        WaterFlowCollectionViewCell *cell = (WaterFlowCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        if (cell) {
            [UIView animateWithDuration:0.25 animations:^{
                cell.transform = CGAffineTransformMakeScale(0.8, 0.8);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.1 animations:^{
                    cell.transform = CGAffineTransformMakeScale(1.0, 1.0);
                } completion:^(BOOL finished) {
                    //这里实现点击cell后要实现的内容
                    if(indexPath.section == 2 || indexPath.section == 1) {
                        AXFBrowserViewController *browser = [AXFBrowserViewController new];
                        browser.jumpURL = [NSURL URLWithString:self.collectionArray[indexPath.section][indexPath.item].customURL];
                        [self.navigationController pushViewController:browser animated:YES];
                    } else {
                        AXFDetailViewController *detailView = [AXFDetailViewController new];
                        if (self.navigationController) {
                            detailView.model = self.collectionArray[indexPath.section][indexPath.item];
                            [self.navigationController pushViewController:detailView animated:YES];
                        }
                    }
                }];
            }];
        }
    }
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row % 2 != 0) {
        cell.transform = CGAffineTransformTranslate(cell.transform, SCREEN_WIDTH / 2, 0);
    }else{
        cell.transform = CGAffineTransformTranslate(cell.transform, - SCREEN_WIDTH / 2, 0);
    }
    cell.alpha = 0.0;
    [UIView animateWithDuration:0.7 animations:^{
        cell.transform = CGAffineTransformIdentity;
        cell.alpha = 1.0;
    } completion:^(BOOL finished) {
        
        
    }];
}

#pragma mark - 配置监听购物车按钮操作通知
- (void)setupNotifications {
    //id observer,  SEL sel, NSString *key
    NotificationCenterAddObserver(self, Action_AXFShoppingButtonView_Plus, @selector(plusClickedNotification:));
    NotificationCenterAddObserver(self, Action_AXFShoppingButtonView_Miuns, @selector(minusClickedNotification:));
    NotificationCenterAddObserver(self, Action_AXFShoppingButtonView_AmountChange, @selector(amountChange:));
}

///增加逻辑
- (void)plusClickedNotification:(NSNotification *)notification {
    //    WaterFlowCollectionViewCell *cell = [self productCellWithShoppingButtonnotification:notification];
    [self animationForNotification:notification];
}
//减少逻辑
- (void)minusClickedNotification:(NSNotification *)notification {
    //    WaterFlowCollectionViewCell *cell = [self productCellWithShoppingButtonnotification:notification];
    
}
//返回对应的cell
- (WaterFlowCollectionViewCell *)productCellWithShoppingButtonnotification:(NSNotification *)notification {
    if ( ![notification.object isKindOfClass:[WaterFlowCollectionViewCell class]] ) {
        return nil;
    }
    WaterFlowCollectionViewCell *cell = notification.object;
    return cell;
}
//购物车数量变化逻辑
- (void)amountChange:(NSNotification *)notification {
    //NSLog(@"总数量 = %ld",_ModelMgr.productTotalAmount);
    NSInteger totalAmont = _ModelMgr.productTotalAmount;
    self.tabBarController.tabBar.items[2].badgeValue = totalAmont > 0 ? [NSString stringWithFormat:@"%ld",_ModelMgr.productTotalAmount] : nil;
}
//按钮动画
- (void)animationForNotification:(NSNotification *)notification{
    WaterFlowCollectionViewCell *cell = [self productCellWithShoppingButtonnotification:notification];
    CGPoint Point = [cell convertPoint:cell.productImageView.center toView:[UIApplication sharedApplication].keyWindow];
    CGRect Bounds = [cell convertRect:cell.productImageView.bounds toView:[UIApplication sharedApplication].keyWindow];
    CGRect StartRect = CGRectMake(Point.x, Point.y, Bounds.size.width, Bounds.size.height);
    CGPoint endPoint = CGPointMake(230, SCREEN_HEIGHT - 20);
    UIImageView *animationImage = [[UIImageView alloc] initWithImage:cell.productImageView.image];
    
    //购物车抖动
    UIView *shopTabBarItem = [self.tabBarController.tabBar subviews][3];
    //UIImageView *imgV = [self.tabBarController.tabBar subviews][3].subviews;
    [[PurchaseCarAnimationTool shareTool] startAnimationandView:animationImage andRect:StartRect andFinisnRect:endPoint andFinishBlock:^(BOOL finish) {
        
        [PurchaseCarAnimationTool shakeAnimation:shopTabBarItem];
    }];
}


//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    [self.collectionView reloadData];
//}
@end
